package com.hlyj.http.base.tool.lib_hlyj_base.net;




import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


public abstract class BaseCallback<T> implements Observer<T> {
    public abstract void onSuccess(T model);
    public abstract void onFailure(String msg);
    public abstract void onFinish();
    @Override
    public void onSubscribe(Disposable d) {
    }
    @Override
    public void onNext(T model) {
        Gson gson=new Gson();
        String obj=gson.toJson(model);
        onSuccess(model);
       // Log.e("qin","基础返回"+obj.toString());
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            String msg = httpException.getMessage();
            if (code == 504) {
                msg = "网络不给力-code"+code;
            }else if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试-code"+code;
            }
            onFailure(msg);
            Log.e("onFailure",msg);
        } else if (e instanceof SocketTimeoutException) {
            onFailure("网络异常,请检查您的网络!");
            Log.e("onFailure","网络请求超时");
        } else if (e instanceof JsonSyntaxException) {
            onFailure("返回内容格式错误");
            Log.e("onFailure","返回内容格式错误");
        } else {
            onFailure(e.getMessage());
            Log.e("onFailure","连接报错"+e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onComplete() {
        onFinish();
    }


}
